﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Newtonsoft.Json;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace aPCSuite
{
    public delegate void DeletegateAddListItem(ListViewItem lvi);
    public delegate void DeletegateDeleteListItem(object obj);
    public delegate void RefereshSMS(object sender, EventArgs e);
    public partial class frmMessaging : Form
    {
        
        public DeletegateAddListItem m_DelegateAddListItem;
        private SMSItems items = null;
        private List<string> items_detail = new List<string>();
        public static string mobile_code = "";
        private Transaction _transaction;
        private frmProgress form5 = null;
        private Thread _request = null;
        private Command _command = null;
        private string id_list = "";
        private int _selected_index = -1;
        public static frmContact _frmContact = null;
        public static List<string> _contact_list = new List<string>();

        public frmMessaging()
        {
            InitializeComponent();

            /*txtCode.Font = new Font(txtCode.Font.Name, 12);

            Font ft = new Font(listView1.Font.Name, 10);
            listView1.Font = ft;
            listView2.Font = ft;/**/

            ImageList imageList = new ImageList();
            imageList.ImageSize = new Size(5, 5);
            System.Drawing.Bitmap bitmap1 = aPCSuite.Properties.Resources.sicon;
            imageList.Images.Add(bitmap1);
            listView1.SmallImageList = imageList;
            m_DelegateAddListItem = new DeletegateAddListItem(this.AddListItem);
            // Create thread for send request and get response from server
            // check active first

            aPCSuite.Properties.Settings set = aPCSuite.Properties.Settings.Default;
            if (set.dev_code != "")
            {
                txtCode.Text = set.dev_code;
                if (Transaction._session_id.Length <= 0)
                {
                    //SMSActive();
                    _command = new Command(REQ_CMD.SMS_ACTIVE);
                }
                else
                {
                    //btnRefresh_Click(null, null);
                    _command = new Command(REQ_CMD.SMS_LIST);
                }
                ThreadPool.QueueUserWorkItem(new WaitCallback(Request_Handler), _command);
            }
            else
            {
                txtCode.Select();
            }
            // data test
            /*for (int i = 0; i < 10; i++)
            {
                ListViewItem lvi = new ListViewItem();
                string address = "012345" + i.ToString();
                lvi.SubItems.Add(address);
                lvi.SubItems.Add("1");
                lvi.SubItems.Add("test");
                lvi.SubItems.Add("test");
                listView1.Items.Add(lvi);
            }/**/
        }

        private void SMSActive()
        {
            if (aPCSuite.Properties.Settings.Default.dev_code.Length > 0)
            {
                if (_transaction != null)
                    _transaction.StopFetch();

                _command = new Command(REQ_CMD.SMS_ACTIVE);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Request_Handler), _command);
            }
            else
            {
                MessageBox.Show("Please enter mobile's code into key textbox");
                txtCode.Focus();
            }/**/
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Transaction._session_id.Length > 0)
            {
                frmNew form2 = new frmNew();
                form2._refresh_sms += new RefereshSMS(btnRefresh_Click);
                form2.ShowDialog();
            }
            else
            {
                SMSActive();
            }
        }

        private void btnFake_Click(object sender, EventArgs e)
        {
            if (Transaction._session_id.Length > 0)
            {
                frmFake form3 = new frmFake();
                form3._refresh_sms += new RefereshSMS(btnRefresh_Click);
                form3.ShowDialog();
            }
            else
            {
                SMSActive();
            }
        }

        private void btnReply_Click(object sender, EventArgs e)
        {
            if (Transaction._session_id.Length > 0)
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    frmReply form4 = new frmReply();
                    form4._refresh_sms += new RefereshSMS(btnRefresh_Click);
                    SMSGroup group = items.GetGroup(listView1.SelectedItems[0].Index);
                    if (group != null)
                        form4.SetReplyAddress(group.address);
                    form4.ShowDialog();
                }
                else
                    MessageBox.Show("Please select item need to reply.");
            }
            else
            {
                SMSActive();
            }
        }

        private string BuildRequest(REQ_CMD cmd)
        {
            string xml = "";
            switch (cmd)
            {
                case REQ_CMD.SMS_LIST:
                    xml = "<protocol encoding=\"UTF-8\" version=\"1.0\">";
                    xml += "<app_id>1</app_id>";
                    xml += "<session_id>" + Transaction._session_id + "</session_id>";
                    xml += "<sms_list>";
                    xml += "<dev_code>" + aPCSuite.Properties.Settings.Default.dev_code + "</dev_code>";
                    xml += "<max_id>" + Transaction._max_id.ToString() + "</max_id>";
                    xml += "<limit>-1</limit>";
                    xml += "</sms_list>";
                    xml += "</protocol>";
                    break;

                case REQ_CMD.FETCH_RESULT:
                    xml = "<protocol encoding=\"UTF-8\" version=\"1.0\">";
                    xml += "<app_id>1</app_id>";
                    xml += "<session_id>" + Transaction._session_id + "</session_id>";
                    xml += "<fetch>";
                    xml += "<dev_code>" + aPCSuite.Properties.Settings.Default.dev_code + "</dev_code>";
                    xml += "</fetch>";
                    xml += "</protocol>";
                    break;

                case REQ_CMD.SMS_DELETE:
                    xml = "<protocol encoding=\"UTF-8\" version=\"1.0\">";
                    xml += "<app_id>1</app_id>";
                    xml += "<session_id>" + Transaction._session_id + "</session_id>";
                    xml += "<sms_del>";
                    xml += "<dev_code>" + aPCSuite.Properties.Settings.Default.dev_code + "</dev_code>";
                    xml += "<id>" + id_list + "</id>";
                    xml += "</sms_del>";
                    xml += "</protocol>";
                    break;

                case REQ_CMD.SMS_UPDATE:
                    xml = "<protocol encoding=\"UTF-8\" version=\"1.0\">";
                    xml += "<app_id>1</app_id>";
                    xml += "<session_id>" + Transaction._session_id + "</session_id>";
                    xml += "<sms_update>";
                    xml += "<dev_code>" + aPCSuite.Properties.Settings.Default.dev_code + "</dev_code>";
                    xml += "<id>" + id_list + "</id>";
                    xml += "<status>R</status>";
                    xml += "</sms_update>";
                    xml += "</protocol>";
                    break;

                case REQ_CMD.SMS_ACTIVE:
                    xml = "<protocol encoding=\"UTF-8\" version=\"1.0\">";
                    xml += "<app_id>1</app_id>";
                    xml += "<sms_active>";
                    xml += "<dev_code>" + aPCSuite.Properties.Settings.Default.dev_code + "</dev_code>";
                    xml += "</sms_active>";
                    xml += "</protocol>";
                    break;
            }
            return xml;
        }

        private void ShowProgressDialog()
        {
            this.Invoke(new MethodInvoker(delegate
                {
                    form5 = new frmProgress();
                    form5._close_event += new close_event(_close_event);
                    form5.SetProgressStatus("Processing...");
                    form5.ShowDialog();
                    //form5.Show(this);
                }));
        }

        private void _close_event(object sender, EventArgs e)
        {
            stop_request();
            if (_transaction != null)
                Transaction.post_trasn_result(_transaction.trans_id, 1);
            // close transaction
            close_trans();
        }

        private void CloseProgressDialog(int status)
        {
            this.Invoke(new MethodInvoker(delegate
            //form5.Invoke(new MethodInvoker(delegate
            {
                try
                {
                    if (form5 != null && form5.manual_cancel == false)
                    {
                        if (status == 0)
                            form5.SetProgressStatus("Successful");
                        else
                            form5.SetProgressStatus("Failed");
                        Thread.Sleep(2000);
                        form5.manual_close = false;
                        form5.Close();
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("CloseProgressDialog exception : {0}", ex.Message);
                }
            }));
        }

        private void request_handler()
        {
            try
            {
                Console.WriteLine("request_handler");
                string req = BuildRequest(_command.req_cmd);
                LogFile.WriteAppendLog("[frmMessaging] request_handler send : " + req, LogFile._LogFile);
                HttpRequestResponse request = new HttpRequestResponse(req, Transaction.uri);
                string res = request.SendRequest();
                LogFile.WriteAppendLog("[frmMessaging] request_handler result : " + res, LogFile._LogFile);
                if (res != "")
                {
                    // XML response: Deserialize XML string to object
                    using (TextReader reader = new StringReader(res))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(protocol));
                        protocol ret = (protocol)serializer.Deserialize(reader);
                        Console.WriteLine("ret");

                        if (Transaction.CodeOk(ret.code))
                        {
                            // start thread to fetch result
                            _transaction = new Transaction();
                            _transaction.trans_id = ret.trans_id;
                            _transaction.cmd = REQ_CMD.FETCH_RESULT;
                            _transaction.callback = new WaitCallback(this.callback);
                            _transaction.StartFetch();
                        }
                        else
                        {
                            if (ret.code == Transaction.OK)
                            {
                                if (ret._sms_active != null)
                                {
                                    if (ret.session_id.Length > 0)
                                    { 
                                        Transaction.post_trasn_result(ret.trans_id, 0);
                                        CloseProgressDialog(0);
                                        Transaction._session_id = ret.session_id;
                                        // Refresh sms list
                                        //btnRefresh_Click(null, null);
                                        this.Invoke(new MethodInvoker(delegate { btnRefresh_Click(null, null); }));
                                    }
                                }
                                else
                                {
                                    // Failed
                                    Transaction.post_trasn_result(ret.trans_id, 1);
                                    CloseProgressDialog(1);
                                }
                            }
                            else
                            {
                                Transaction.post_trasn_result(ret.trans_id, 1);
                                CloseProgressDialog(1);
                                if (ret.code == Transaction.TV_APP_NOT_ACTIVED)
                                {
                                    // Show message active here
                                    MessageBox.Show("Your's mobile code have not activating, please contact with developer to active your mobile's code\nContact Email: contact@ninemobi.com or david.nguyen2006@gmail.com\nContact Phone: 0937997639");
                                }
                            }
                        }
                    }
                }
                else
                    CloseProgressDialog(1);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("request_handler exception : {0}", ex.Message);
            }
        }

        public void Request_Handler(object state)
        {
            try
            {
                stop_request();
                close_trans();
                _request = new Thread(new ThreadStart(request_handler));
                _request.Start();
                Thread.Sleep(100);
                ShowProgressDialog();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Request_Handler exception : {0}", ex.Message);
            }
        }

        private void ShowSMS(SMSItems items)
        {
            if (items != null)
            {
                // clear list view
                this.Invoke(new MethodInvoker(delegate
                { 
                    listView1.Items.Clear(); 
                
                    foreach (SMSGroup item in items.group_list)
                    {
                        int count = item.sms_list.Count;

                        /*var enumerator = item.Value.sms_list.Values.GetEnumerator();
                        enumerator.MoveNext();
                        sms _sms = enumerator.Current;/**/

                        //sms _sms = item.sms_list[count - 1];
                        sms _sms = item.sms_list[0];
                        ListViewItem lvi = new ListViewItem();
                        string address = (_sms.from != "" ? _sms.from : _sms.to);
                        lvi.SubItems.Add(address);
                        lvi.SubItems.Add(count.ToString());
                        lvi.SubItems.Add(_sms.content);
                        lvi.SubItems.Add(_sms.create_date);
                        if (item.status == "N")
                            lvi.ImageIndex = 0;
                        //this.Invoke(m_DelegateAddListItem, new object[] { lvi });
                        listView1.Items.Add(lvi);
                    }
                    if (_selected_index >= 0 && _selected_index < listView1.Items.Count)
                    {
                        listView1.Items[_selected_index].Selected = true;
                        //listView1_SelectedIndexChanged(null, null);
                    }
                    else
                        listView2.Items.Clear();
                }));
            }
        }

        private void AddListItem(ListViewItem lvi)
        {
            listView1.Items.Add(lvi);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*listView2.Items.Clear();
            ListViewItem lvi1 = new ListViewItem("0123");
            lvi1.SubItems.Add("aaa");
            lvi1.SubItems.Add("bbb");
            listView2.Items.Add(lvi1);
            return;/**/
            if (listView1.SelectedItems.Count > 0)
            {
                SMSGroup group = GetGroupSelectedItem();
                Console.WriteLine("Selected index : {0}", listView1.SelectedItems[0].Index);
                // Show group detail
                if (group != null)
                {
                    // clear list view
                    listView2.Items.Clear();
                    foreach (sms _sms in group.sms_list)
                    {
                        string address = (_sms.type == 2 ? "Me" : _sms.from);
                        ListViewItem lvi = new ListViewItem(address);
                        lvi.SubItems.Add(_sms.content);
                        lvi.SubItems.Add(_sms.create_date);
                        listView2.Items.Add(lvi);
                    }/**/
                    /*foreach (KeyValuePair<string, sms> item in group.sms_list)
                    {
                        sms _sms = item.Value;
                        string address = (_sms.type == 2 ? "Me" : _sms.from);
                        ListViewItem lvi = new ListViewItem(address);
                        lvi.SubItems.Add(_sms.content);
                        lvi.SubItems.Add(_sms.create_date);
                        listView2.Items.Add(lvi);
                    }/**/

                    // update status
                    if (group.status == "N")
                    {
                        ChangeSmsStatus(group);
                    }
                }
            }
        }

        private void ChangeSmsStatus(SMSGroup group)
        {
            if (group.status == "N")
            {
                id_list = "";
                foreach (sms _sms in group.sms_list)
                {
                    if(_sms.status == "N")
                        id_list += (_sms.id + ",");
                }
                if (id_list.Length > 0)
                {
                    id_list = id_list.Substring(0, id_list.Length - 1);
                    if (id_list.Length > 0)
                    {
                        // Delete sms
                        _command = new Command(REQ_CMD.SMS_UPDATE);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(Request_Handler), _command);
                    }
                }
            }
        }

        private bool DeleteSMSList(string id_list)
        {
            bool need_get_sms_max_id = false;
            if (id_list.Length > 0)
            {
                string[] id_list_split = id_list.Split(',');
                for (int i = 0; i < id_list_split.Length; ++i)
                {
                    string[] id_split = id_list_split[i].Split('$');
                    int thread_id;
                    int sms_id;
                    if (Int32.TryParse(id_split[0], out thread_id) && Int32.TryParse(id_split[1], out sms_id))
                    {
                        if (sms_id > Transaction._max_id)
                            need_get_sms_max_id = true;

                        SMSGroup sms_group = items.GetGroupById(thread_id);
                        if (sms_group != null)
                        {
                            sms_group.RemoveSMSById(sms_id);
                            /*foreach (sms _sms in sms_group.sms_list)
                            {
                                if (sms_id == _sms.id)
                                    sms_group.sms_list.Remove(_sms);
                            }/**/

                            if (sms_group.Count() == 0)
                                // remove this group
                                items.RemoveGroup(sms_group);
                        }
                    }
                }
            }
            return need_get_sms_max_id;
        }

        private void GroupSMS(sms_list _sms_list)
        {
            if(items == null)
                items = new SMSItems();

            // check delete first
            bool need_get_sms_max_id = DeleteSMSList(_sms_list.id_list);

            // group sms
            if (_sms_list.arr_sms != null)
            {
                for (int i = 0; i < _sms_list.arr_sms.Length; ++i)
                {
                    sms _sms = _sms_list.arr_sms[i];
                    // find sms max id
                    if (need_get_sms_max_id == false)
                    {
                        if (Transaction._max_id < _sms.id)
                            Transaction._max_id = _sms.id;
                    }
                    // find group
                    SMSGroup sms_group = items.GetGroupById(_sms.thread_id);
                    if (sms_group == null)
                    {
                        sms_group = new SMSGroup();

                        sms_group.max_date = _sms.create_date;
                        sms_group.thread_id = _sms.thread_id;
                        sms_group.address = (_sms.from != "" ? _sms.from : _sms.to);

                        items.AddBinary(sms_group);
                    }

                    if (_sms.status == "N")
                        sms_group.status = _sms.status;
                    if (sms_group.address == "")
                        sms_group.address = (_sms.from != "" ? _sms.from : _sms.to);

                    if (sms_group.max_date.CompareTo(_sms.create_date) == -1)
                    {
                        // remove from list and add again
                        sms_group.max_date = _sms.create_date;
                        items.RemoveGroup(sms_group);
                        items.AddBinary(sms_group);
                    }
                    //_sms.create_date = Transaction.ConvertUtcToLocalDateTime(_sms.create_date);

                    //sms_group.Add(_sms);
                    sms_group.AddBinary(_sms);

                    //sms_group.Add(_sms.id.ToString(), _sms);
                }
            }

            if (need_get_sms_max_id)
                Transaction._max_id = SMSMaxID();
        }

        private int SMSMaxID()
        {
            int max = 0;
            if (items != null)
            {
                foreach (SMSGroup item in items.group_list)
                {
                    foreach (sms _sms in item.sms_list)
                    {
                        if (max < _sms.id)
                            max = _sms.id;
                    }
                }
            }
            return max;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (Transaction._session_id.Length > 0)
            {
                if (txtCode.Text.Length > 0)
                {
                    if (_transaction != null)
                        _transaction.StopFetch();

                    _command = new Command(REQ_CMD.SMS_LIST);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Request_Handler), _command);
                }
            }
            else
            {
                SMSActive();
            }
        }

        private void callback(object sender)
        {
            try
            {
                protocol ret = sender as protocol;
                if (ret != null)
                {
                    if (ret.trans_id == _transaction.trans_id)
                    {
                        if (ret.code == Transaction.OK)
                        {
                            CloseProgressDialog(0);
                            if (ret._sms_list != null)
                            {
                                GroupSMS(ret._sms_list);
                                ShowSMS(items);
                            }
                            else
                            {
                                // deleted sms
                                //if (id_list != "")
                                if(ret._sms_del != null)
                                {
                                    this.Invoke(new DeletegateDeleteListItem(this.DeleteListViewItem), new object[] {null});
                                }
                                else if (ret._sms_update != null)
                                {
                                    // updated sms
                                    this.Invoke(new MethodInvoker(delegate
                                    {
                                        try
                                        {
                                            if (listView1.SelectedItems.Count > 0)
                                            {
                                                ListViewItem item = listView1.SelectedItems[0] as ListViewItem;
                                                item.ImageIndex = -1;
                                                listView1.Refresh();
                                                SMSGroup group = GetGroupSelectedItem();
                                                if (group != null)
                                                    group.status = "R";
                                            }
                                        }
                                        catch (System.Exception ex)
                                        {
                                            Console.WriteLine("Change status failed : {0}", ex.Message);
                                            LogFile.WriteAppendLog("Change status failed : " + ex.Message, LogFile._LogFile);
                                        }
                                    }));
                                }
                                /*else if (ret._sms_active != null)
                                {
                                    Transaction._session_id = ret.session_id;
                                    // Refresh sms list
                                    //btnRefresh_Click(null, null);
                                    this.Invoke(new MethodInvoker(delegate { btnRefresh_Click(null, null); }));
                                }/**/
                            }
                            Transaction.post_trasn_result(ret.trans_id, 0);
                        }
                        else if (!Transaction.CodeOk(ret.code))
                        {
                            CloseProgressDialog(1);
                            Transaction.post_trasn_result(ret.trans_id, 1);
                            /*if (ret.code == Transaction.TV_APP_NOT_ACTIVED)
                            {
                                // Show message active here
                                MessageBox.Show("Your's mobile code have not activating, please contact with developer to active your mobile's code, Contact Phone: 0937997639");
                            }/**/
                        }
                    }
                    else
                    {
                        CloseProgressDialog(1);
                        Transaction.post_trasn_result(ret.trans_id, 1);
                    }
                }
                else
                {
                    CloseProgressDialog(1);
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Callback exception : {0}", ex.Message);
                LogFile.WriteAppendLog("Callback exception : " + ex.Message, LogFile._LogFile);
            }
        }

        private void DeleteListViewItem(object obj)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                SMSGroup group = GetGroupSelectedItem();
                bool need_get_sms_max_id = false;
                foreach (ListViewItem item in listView2.SelectedItems)
                {
                    // remove data in the memory
                    int id = group.RemoveSMSAt(item.Index);
                    if (id > Transaction._max_id)
                        need_get_sms_max_id = true;
                    // remove from GUI
                    listView2.Items.Remove(item);
                }
                if (group.Count() == 0)
                {
                    items.RemoveGroup(group);
                    //_selected_index = -1;
                }
                ShowSMS(items);
                if (need_get_sms_max_id)
                    Transaction._max_id = SMSMaxID();
            }
            else if (listView1.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    // remove data in the memory
                    items.RemoveGroupAt(item.Index);
                    // remove from GUI
                    listView1.Items.Remove(item);
                    listView2.Items.Clear();
                    Transaction._max_id = SMSMaxID();
                    //_selected_index = -1;
                }
            }
        }

        private void txtCode_Leave(object sender, EventArgs e)
        {
            aPCSuite.Properties.Settings set = aPCSuite.Properties.Settings.Default;
            if (set.dev_code != txtCode.Text)
            {
                Transaction._session_id = "";
                // clear list
                listView1.Items.Clear();
                listView2.Items.Clear();
            }
            set.dev_code = txtCode.Text;
            set.Save();
        }

        private void stop_request()
        {
            if (_request != null)
            {
                _request.Abort();
                _request.Join();
            }
        }

        private void close_trans()
        {
            if (_transaction != null)
                _transaction.StopFetch();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            stop_request();
            close_trans();
        }

        private void listView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (listView2.SelectedItems.Count > 0)
                {
                    DeleteProcess();
                }
            }
        }

        private void listView2_MouseDown(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Right:
                    {
                        if (listView2.SelectedItems.Count > 0 && listView1.SelectedItems.Count > 0)
                        {
                            id_list = "";
                            SMSGroup group = GetGroupSelectedItem();
                            if (group != null)
                            {
                                for (int i = 0; i < listView2.SelectedItems.Count; ++i)
                                {
                                    sms _sms = group.sms_list[listView2.SelectedItems[i].Index];
                                    id_list += (_sms.id + ",");
                                }
                                id_list = id_list.Substring(0, id_list.Length - 1);
                            }
                            contextMenuStrip1.Show(Cursor.Position);
                        }
                    }
                    break;
            }
        }

        private void DeleteProcess()
        {
            DialogResult result1 = MessageBox.Show("Do you want to delete this message?",
                        "Confirm",
                        MessageBoxButtons.YesNo);
            if (result1 == DialogResult.Yes)
            {
                // Delete sms
                _command = new Command(REQ_CMD.SMS_DELETE);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Request_Handler), _command);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnReply_Click(null, null);
        }

        private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DeleteProcess();
        }

        private SMSGroup GetGroupSelectedItem()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                _selected_index = listView1.SelectedItems[0].Index;
                SMSGroup group = items.GetGroup(listView1.SelectedItems[0].Index);
                return group;
            }
            return null;
        }

        private void listView1_MouseDown(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Right:
                    {
                        // create id list
                        if (listView1.SelectedItems.Count > 0)
                        {
                            id_list = "";
                            SMSGroup group = GetGroupSelectedItem();
                            if (group != null)
                            {
                                foreach (sms _sms in group.sms_list)
                                {
                                    id_list += (_sms.id + ",");
                                }
                                id_list = id_list.Substring(0, id_list.Length - 1);
                            }
                            contextMenuStrip1.Show(Cursor.Position);
                        }
                        
                    }
                    break;
            }
        }

        private void listView2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Console.WriteLine("listView2_MouseDoubleClick");
            
            if (listView2.SelectedItems.Count > 0 && listView1.SelectedItems.Count > 0)
            {
                string msg_content = "";
                SMSGroup group = GetGroupSelectedItem();
                if (group != null)
                {
                    for (int i = 0; i < listView2.SelectedItems.Count; ++i)
                    {
                        sms _sms = group.sms_list[listView2.SelectedItems[i].Index];
                        msg_content += (_sms.content + "\r\n");
                    }
                    msg_content = msg_content.Substring(0, msg_content.Length - 2);

                    frmMsgEdit frmEdit = new frmMsgEdit();
                    frmEdit.setMsgContent(msg_content);
                    frmEdit.ShowDialog();
                }
            }
        }
    }
}
